package com.yangye.pidoublename.service.impl;

import com.yangye.pidoublename.service.DoubleNameService;
import com.yangye.pidoublename.service.ProvinceEnum;
import com.yangye.pidoublename.vo.DoubleNameVo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author yangye
 * @date 2019/9/19
 */
@Service
public class HeNanServiceImpl implements DoubleNameService {
	@Autowired
	private RestTemplate restTemplate;

	private final String QUERY_URL = "http://bsdt.henanga.gov.cn/MainPages/ChaXunZhongXin/SameNameQuery";

	@Override
	public DoubleNameVo findByName(String name) {
		MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
		params.add("form_areaid", "410000");
		params.add("form_Name", name);
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
		HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(params, httpHeaders);
		ResponseEntity<String> response = restTemplate.postForEntity(QUERY_URL, request, String.class);
		String body = response.getBody();

		/**
		 * 解析html片段
		 * <div id="dvQuerySearch" class="cmcx_cxjg">
		 * 	<div class="cmcx_cxjg_lf">
		 * 		<p class="text01">54</p>
		 * 		<p class="text02">重名人数</p>
		 * 	</div>
		 * 	<div class="cmcx_cxjg_rt">
		 * 		<div class="cmcx_cxjg_rt_main">
		 * 			<p class="borderb">查询姓名:<b>杨野</b></p>
		 * 			<p>查询范围:<b>河南省</b></p>
		 * 		</div>
		 * 	</div>
		 * </div>
		 */
		Document doc = Jsoup.parse(body);
		int total = Integer.parseInt(doc.select(".text01").first().text());

		DoubleNameVo doubleNameVo = new DoubleNameVo();
		doubleNameVo.setProvince(ProvinceEnum.HENAN.getName());
		doubleNameVo.setName(name);
		doubleNameVo.setTotal(total);
		return doubleNameVo;
	}
}
